<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller;

use app\service\uploads\UploadService;
use app\common\model\SystemUploads;
use think\facade\Db;

class Upload extends Base
{
    /**
     * File upload
     * @auth false
     */
    public function upload()
    {
        $app     = request()->post('app', 'admin');
        $file    = request()->file('file');
        $type    = request()->post('type', 'auto'); // Default automatic detection type
        $user_id = $this->user->id;

        if ($file?->isValid()) {
            try {
                $res = (new UploadService())->upload($app, $file, $type, $user_id);
            } catch (\Exception $e) {
                $this->error($e->getMessage(), [
                    'error' => $e->getMessage(),
                ]);
            }
            $this->success(trans('upload_successful'), $res);

        } else {
            $this->error(trans('please_select_file'));
        }
    }

    /**
     * Get supported file types
     */
    public function getFileTypes()
    {
        $mime_config = config('site.upload.mime');
        $types       = [];

        foreach ($mime_config as $type => $config) {
            if ($type !== 'all') {
                $types[] = [
                    'value'      => $type,
                    'label'      => $this->getFileTypeLabel($type),
                    'extensions' => $config['ext'] ?? [],
                    'icon'       => $config['icon'] ?? 'file'
                ];
            }
        }

        return $this->success('', ['types' => $types]);
    }

    /**
     * Get file type display name
     */
    protected function getFileTypeLabel($type)
    {
        $labels = [
            'image'        => trans('image'),
            'video'        => trans('video'),
            'audio'        => trans('audio'),
            'document'     => trans('document'),
            'spreadsheet'  => trans('spreadsheet'),
            'presentation' => trans('presentation'),
            'archive'      => trans('archive'),
            'code'         => trans('code'),
            'certificate'  => trans('certificate'),
            'other'        => trans('other')
        ];

        return $labels[$type] ?? $type;
    }

    /**
     * Image category
     */
    public function getCategoryList()
    {
        $app  = inputs('app', 'admin');
        $list = Db::name('system_uploads_category')->where([
            'app'     => $app,
            'user_id' => $this->user->id
        ])->order('id desc')->select()->toArray();
        $tree = [];
        foreach ($list as $item) {
            $tree[$item['id']] = $item;
        }
        foreach ($tree as $key => $item) {
            $tree[$item['pid']]['children'][] = &$tree[$key];
        }

        $tree = $tree[0]['children'] ?? [];

        $this->success('', [
            'list' => $tree
        ]);
    }

    /**
     * Create category
     */
    public function createCategory()
    {
        $app     = inputs('app', 'admin');
        $name    = inputs('name');
        $pid     = inputs('pid', 0);
        $user_id = $this->user->id;
        empty($name) && $this->error(trans('category_name_required'));
        $data = [
            'app'     => $app,
            'name'    => $name,
            'pid'     => $pid,
            'user_id' => $user_id
        ];
        $res  = Db::name('system_uploads_category')->insert($data);
        return $res ? $this->success() : $this->error();
    }

    /**
     * Edit category
     */
    public function editCategory()
    {
        $id   = inputs('id/d', 0);
        $name = inputs('name');
        empty($name) && $this->error(trans('category_name_required'));
        $res = Db::name('system_uploads_category')->where([
            'id' => $id,
        ])->update([
                    'name' => $name
                ]);
        return $res ? $this->success() : $this->error();
    }

    /**
     * Delete category
     */
    public function deleteCategory()
    {
        $id  = inputs('ids/d', 0);
        $res = Db::name('system_uploads_category')->where([
            'id' => $id,
        ])->delete();
        $res && Db::name('system_uploads')->where([
            'cate_id' => $id,
        ])->update([
                    'cate_id' => 0
                ]);
        return $res ? $this->success() : $this->error();
    }

    /**
     * File list
     */
    public function fileList()
    {
        $limit     = inputs('limit', '12');
        $name      = inputs('name');
        $cate_id   = inputs('cate_id', 0);
        $file_icon = inputs('file_icon', ''); // File type filter
        $extension = inputs('extension', ''); // File extension filter
        $user_id   = inputs('user_id', 0);
        $app       = inputs('app', 'admin');

        $where = [];
        if ($user_id) {
            $where['user_id'] = $user_id;
        }
        if ($app) {
            $where['app'] = $app;
        }
        if ($name) {
            $where['name'] = ['like', "%$name%"];
        }
        if ($cate_id) {
            $where['cate_id'] = $cate_id;
        }
        // Filter by file type
        if (!empty($file_icon)) {
            $where['file_icon'] = $file_icon;
        }

        // Filter by file extension
        if (!empty($extension)) {
            $where['ext'] = $extension;
        }


        $res = SystemUploads::where($where)->order('id desc')->paginate($limit);

        // Get file type statistics
        $typeStats = SystemUploads::group('file_icon')->column('COUNT(*)', 'file_icon');

        // Get common extension statistics
        $extStats = SystemUploads::group('ext')->column('COUNT(*)', 'ext');

        $this->success('', [
            'list'       => $res->items(),
            'total'      => $res->total(),
            'type_stats' => $typeStats,
            'ext_stats'  => $extStats
        ]);
    }

    /**
     * Modify name
     */
    public function fileUpdateApi()
    {
        $id   = inputs('id/d', 0);
        $name = inputs('name');

        empty($name) && $this->error(trans('name_required', [], 'upload'));
        mb_strlen($name) > 20 && $this->error(trans('name_too_long', [], 'upload'));

        $data = ['name' => $name];



        $res = SystemUploads::where([
            'id' => $id,
        ])->update($data);

        return $res ? $this->success(trans('modify_successful', [], 'upload')) : $this->error(trans('modify_failed', [], 'upload'));
    }

    /**
     * Batch delete images
     */
    public function delete()
    {
        $ids = inputs('ids');
        empty($ids) && $this->error(trans('please_select_file'));
        if(is_array($ids)) {
            $where[] = ['id', 'in', $ids];
        } else {
            $where[] = ['id', '=', $ids];
        }
        $res = SystemUploads::where($where)->delete();
        return $res ? $this->success() : $this->error();
    }

    /**
     * Save URL image
     */
    public function saveUrlImage()
    {
        $url     = inputs('url');
        $name    = inputs('name');
        $cate_id = inputs('cate_id', 0);
        $user_id = $this->user->id;

        // Verify URL
        empty($url) && $this->error(trans('image_url_required'));

        // Verify URL format
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            $this->error(trans('please_enter_valid_url'));
        }

        // Verify if it is an image URL
        $image_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
        $url_path         = parse_url($url, PHP_URL_PATH);
        $extension        = strtolower(pathinfo($url_path, PATHINFO_EXTENSION));

        if (!in_array($extension, $image_extensions)) {
            $this->error(trans('url_must_point_to_image_file'));
        }

        // If no name is provided, extract it from the URL
        if (empty($name)) {
            $name = pathinfo($url_path, PATHINFO_FILENAME) ?: trans('url_image');
        }

        // Verify if the URL is accessible (optional, may increase response time)
        try {
            $headers = get_headers($url, 1);
            if (!$headers || strpos($headers[0], '200') === false) {
                $this->error(trans('cannot_access_image_url'));
            }
        } catch (\Exception $e) {
            // error_log($e->getMessage());
        }

        // Save to database
        $data = [
            'cate_id'       => $cate_id,
            'name'          => $name,
            'url'           => $url,
            'file_size'     => 0, // URL image cannot get accurate size
            'ext'           => $extension,
            'storage'       => 'url', // Mark as URL storage
            'file_type'     => 'image',
            'file_icon'     => 'file-image',
            'original_name' => $name,
            'user_id'       => $user_id,
            'create_time'   => time(),
            'update_time'   => time(),
        ];

        /** @var SystemUploads $res */
        $res = SystemUploads::create($data);

        if ($res) {
            $this->success('', [
                'id'   => $res->id,
                'url'  => $url,
                'name' => $name
            ]);
        } else {
            $this->error();
        }
    }
}